package com.feicheng.common.advice;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.feicheng.common.constant.Constant;
import com.feicheng.common.exception.SystemException;
import com.feicheng.common.result.ResultInfo;

import lombok.extern.slf4j.Slf4j;


@ControllerAdvice
@Slf4j
public class ControllerAdviceHandler {

    @ResponseBody
    @ExceptionHandler(SystemException.class)
    public ResultInfo handlerSystemException(SystemException e) {
        ResultInfo resultInfo = ResultInfo.fail(e.getMessage());
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        Boolean newSessionFlg = (Boolean) request.getAttribute("NEWSESSION");
        if (null != newSessionFlg && newSessionFlg) {
            resultInfo.put(Constant.RESULT.SESSIONID, request.getAttribute(Constant.RESULT.SESSIONID));
        }
        log.warn("业务逻辑执行失败：URL:" + request.getRequestURI()+" CODE:"+ e.getCode()+" MESSAGE:"+e.getMessage());
        if (null != e.getCode()) {
            resultInfo.put(Constant.RESULT.CODE, e.getCode());
        }
        return resultInfo;
    }

    @ResponseBody
    @ExceptionHandler(Exception.class)
    public ResultInfo handlerException(Exception e) {
        ResultInfo resultInfo = ResultInfo.error("系统出现未知错误！");
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        Boolean newSessionFlg = (Boolean) request.getAttribute("NEWSESSION");
        if (null != newSessionFlg && newSessionFlg) {
            resultInfo.put(Constant.RESULT.SESSIONID, request.getAttribute(Constant.RESULT.SESSIONID));
        }
        log.error("业务逻辑执行错误：URL " + request.getRequestURI(), e);
        return resultInfo;
    }

}